<?php

require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Model.php';

class PipesCore_Models_Savers_TagRelationshipSaver
{
	private $_model = null;
	private $_mapper = null;

	public function __construct(PipesImpl_Config $config, PipesImpl_Model $model) {
		$this->_model = $model;
		$factory = new Pipes_Model_Mapper_Factory($config);
		$this->_mapper = $factory->factory('tag');
	}

	public function save() {
		if (is_object($this->_model->tags)) {
			// don't do anything with this - it's already a loaded TagList
			return;
		}

		$tags = explode(' ', $this->_model->tags);
		unset($this->_model->tags);
		
		$currentTags = array();
		foreach ($this->_model->tags as $existingTag) {
			$tagAlreadyExists = array_search($existingTag->name, $tags);
			
			if ($tagAlreadyExists === false) {
				// existing tag is no longer present
				$this->_model->tags->removeCurrent();
			} else {
				// tag already exists, no need to add it again
				unset($tags[$tagAlreadyExists]);
			}
		}

		// what's left in the $tags array are new tags, we need to add
		foreach ($tags as $tag) {
			if (empty($tag)) {
				continue;
			}

			$filter = new Pipes_Filter();
			$filter->name->equals($tag);

			$existingTag = $this->_mapper->find($filter);
			$tagObj = $this->_model->tags->add($existingTag);
			$tagObj->name = $tag;
			$tagObj->save();
		}
	}
}
